package com.omt.tarjimdinek.printer;

import static com.google.common.collect.Maps.newHashMap;
import static org.hibernate.proxy.HibernateProxyHelper.getClassWithoutInitializingProxy;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.format.Printer;

/**
 * Given the type of the object use the corresponding {@link org.springframework.format.Printer}, or use toString method.
 * 
 * @see org.springframework.format.Printer
 * @see DiscoverablePrinter
 */
@Named("typeAwarePrinter")
@SuppressWarnings("rawtypes")
public class TypeAwarePrinter implements Printer {
    private Map<Class, DiscoverablePrinter<?>> printers = newHashMap();

//    @Inject
//    void buildCache(List<DiscoverablePrinter> discoverablePrinter) {
//        for (DiscoverablePrinter printer : discoverablePrinter) {
//            printers.put(printer.getTarget(), printer);
//        }
//    }

    /**
     * return the string representation using the current {@link Locale}
     */
    public String print(Object document) {
        return print(document, LocaleContextHolder.getLocale());
    }

    @SuppressWarnings("unchecked")
    @Override
    public String print(Object object, Locale locale) {
        DiscoverablePrinter printer = printers.get(getClassWithoutInitializingProxy(object));
        if (printer == null) {
            return object == null ? "" : object.toString();
        }
        return printer.print(object, locale);
    }
}